package com.kili.file.config.factory;


import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.kili.file.config.factory.subabstract.AbstractCloudFactoryBean;
import com.kili.file.config.systemparam.FileUploadS3ParamConfig;
import com.kili.file.service.FileUploadService;
import com.kili.file.service.impl.FileUploadWithS3CloudStorage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;

/**
 * @author Gordon
 * @version 2019/5/28
 */
@Slf4j
public class S3CloudFileUploadFactoryBean extends AbstractCloudFactoryBean implements FactoryBean<FileUploadService> {

    @Autowired
    private FileUploadS3ParamConfig fileUploadS3ParamConfig;

    @Override
    public Object coreWithHandler(Object o) {
        return null;
    }

    @Nullable
    @Override
    public FileUploadService getObject() {
        fileUploadWithS3CloudStorage.setFileUploadS3ParamConfig(fileUploadS3ParamConfig);
        AmazonS3 s3 = initClient();
        createBucketIfNot(s3);
        fileUploadWithS3CloudStorage.setS3(s3);
        log.info("Initialized class [" + FileUploadWithS3CloudStorage.class.getSimpleName() + "] for factory bean");
        return fileUploadWithS3CloudStorage;
    }

    @Nullable
    @Override
    public Class<?> getObjectType() {
        return FileUploadWithS3CloudStorage.class;
    }

    @Override
    public boolean isSingleton() {
        return IS_SINGLETON;
    }


    private AmazonS3 initClient() {
        AWSCredentials credentials = new BasicAWSCredentials(fileUploadS3ParamConfig.getAccessKey(),
                fileUploadS3ParamConfig.getAccessSecret());
        AWSCredentialsProvider provider = new AWSStaticCredentialsProvider(credentials);
        ClientConfiguration clientConfiguration = new ClientConfiguration();
        clientConfiguration.setProtocol(Protocol.HTTP);

        return AmazonS3ClientBuilder.standard()
                .withRegion(fileUploadS3ParamConfig.getRegions())
                .withCredentials(provider)
                .withClientConfiguration(clientConfiguration)
                .build();

    }

    private void createBucketIfNot(AmazonS3 s3) {
        if (!s3.doesBucketExistV2(fileUploadS3ParamConfig.getBucketName())) {
            s3.createBucket(fileUploadS3ParamConfig.getBucketName());
        }
    }
}
